package com.demo.ipandmac;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * @author wangning
 * @date 2023/11/2 20:08
 */
public class GetMac {

    public static void main(String[] args) throws UnknownHostException {
//        InetAddress inetAddress = InetAddress.getLocalHost();
//        System.out.println(getLocalMac(inetAddress));
        getMac();
    }

    /**
     * 获取本地mac地址
     * 注意：物理地址是48位，别和ipv6搞错了
     *
     * @param inetAddress Localhost
     * @return 本地mac地址
     */
    private static String getLocalMac(InetAddress inetAddress) {
        try {
            //获取网卡，获取地址
            byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                if (i != 0) {
                    sb.append("-");
                }
                //字节转换为整数
                int temp = mac[i] & 0xff;
                String str = Integer.toHexString(temp);
                if (str.length() == 1) {
                    sb.append("0").append(str);
                } else {
                    sb.append(str);
                }
            }
            return sb.toString();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void getMac() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                if (networkInterface.isUp() && !networkInterface.isLoopback() && !networkInterface.isVirtual()) {
                    byte[] macAddressBytes = networkInterface.getHardwareAddress();
                    if (macAddressBytes != null) {
                        StringBuilder macAddress = new StringBuilder();
                        for (byte b : macAddressBytes) {
                            macAddress.append(String.format("%02X:", b));
                        }
                        if (macAddress.length() > 0) {
                            macAddress.deleteCharAt(macAddress.length() - 1);
                        }
                        System.out.println("MAC Address: " + macAddress);
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }





}
